/**
 * 本模块用于获取直播间信息、ws地址
 */

require("../lib/signature.js");
const cookie = require("cookie");
const axios = require("axios");


/**
 * 根据liveId获取直播房间信息
 */
async function fetchLiveRoomInfo(liveId) {
  try {
    const url = "https://live.douyin.com/" + liveId;
    const res = await axios.get(url, {
      headers: {
        Cookie: "__ac_nonce=063abcffa00ed8507d599",
      },
    });
    let html = res.data;
    const matchRes = html.match(
      /<script\snonce="\S+?"\s>self\.__pace_f\.push\(\[1,"[a-z]?:\[\\"\$\\",\\"\$L\d+\\",null,([\s\S]+?)\]\\n"\]\)<\/script>/
    );
    const REGLIST = [
      {
        reg: /\\{1,7}"/g,
        str: '"',
      },
      {
        reg: /"\{/g,
        str: "{",
      },
      {
        reg: /\}"/g,
        str: "}",
      },
      {
        reg: /"\[/g,
        str: "[",
      },
      {
        reg: /\]"/g,
        str: "]",
      },
    ];
    if (!matchRes) throw new Error("房间信息获取失败");
    let json = matchRes[1];
    for (const REG of REGLIST) {
      json = json.replace(REG.reg, REG.str);
    }
    const dict = JSON.parse(json);
    let roomId = dict["state"]["roomStore"]["roomInfo"]["roomId"];
    let roomTitle = dict["state"]["roomStore"]["roomInfo"]["room"]["title"];
    let roomUserCount =
      dict["state"]["roomStore"]["roomInfo"]["room"]["user_count_str"];
    let uniqueId = dict["state"]["userStore"]["odin"]["user_unique_id"];
    const ttwid = cookie.parse(res.headers["set-cookie"][0])["ttwid"];

    return { roomId, roomTitle, roomUserCount, uniqueId, ttwid };
  } catch (error) {
    console.error(error);
  }
}

/**
 * 获取ws地址
 */
const getDyWsUrl = (roomId, uniqueId) => {
    const sign = window.getSign(roomId, uniqueId)["X-Bogus"];
    const now = Date.now();
    const wsUrl = `wss://webcast3-ws-web-hl.douyin.com/webcast/im/push/v2/?app_name=douyin_web&version_code=180800&webcast_sdk_version=1.3.0&update_version_code=1.3.0&compress=gzip&internal_ext=internal_src:dim|wss_push_room_id:${roomId}|wss_push_did:${uniqueId}|fetch_time:${now}|seq:1|wss_info:0-${now}-0-0&cursor=t-${now}_r-1_d-1_u-1_h-1&host=https://live.douyin.com&aid=6383&live_id=1&did_rule=3&debug=false&maxCacheMessageNumber=20&endpoint=live_pc&support_wrds=1&im_path=/webcast/im/fetch/&user_unique_id=${uniqueId}&device_platform=web&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_version=5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/111.0.0.0%20Safari/537.36%20Edg/111.0.1661.62&browser_online=true&tz_name=Asia/Shanghai&identity=audience&room_id=${roomId}&heartbeatDuration=0&signature=${sign}`;
    return wsUrl;
}


module.exports = {
    fetchLiveRoomInfo,
    getDyWsUrl
}